# services.py
from datetime import timezone
import uuid
from django.db import transaction
from .models import Message, MessageThread

class MessageSyncService:
    @staticmethod
    def sync_messages(thread_id: str, message_data_list: list) -> tuple:
        """
        同步消息数据，自动跳过已同步的消息
        
        Args:
            thread_id: 对话线程ID
            message_data_list: 包含消息详情的列表，每个元素需包含:
                - external_id: 外部系统唯一标识
                - sender: 发送者类型
                - content: 消息内容
                - created_at: 消息创建时间
                - 其他需要保存的字段...
        
        Returns:
            tuple: (新增消息数量, 已存在消息数量)
        """
        try:
            thread = MessageThread.objects.get(thread_id=thread_id)
            new_count = 0
            existing_count = 0
            
            with transaction.atomic():
                for msg_data in message_data_list:
                    external_id = msg_data.get('external_id')
                    if not external_id:
                        continue
                        
                    # 使用get_or_create避免重复创建
                    obj, created = Message.objects.get_or_create(
                        thread=thread,
                        external_id=external_id,
                        defaults={
                            'sender': msg_data.get('sender', 'BUYER'),
                            'message_id': msg_data.get('message_id', str(uuid.uuid4())),
                            'content': msg_data.get('content', ''),
                            'created_at': msg_data.get('created_at', timezone.now()),
                        }
                    )
                    
                    if created:
                        new_count += 1
                    else:
                        existing_count += 1
                        
            return new_count, existing_count
            
        except MessageThread.DoesNotExist:
            raise ValueError(f"对话线程 {thread_id} 不存在")
        except Exception as e:
            # 记录详细错误日志
            import logging
            logger = logging.getLogger(__name__)
            logger.error(f"同步消息失败: {str(e)}", exc_info=True)
            raise